package com.mall.mymall.utils;

import com.alibaba.fastjson.JSON;
import com.mall.mymall.dao.entity.Administrators;
import com.mall.mymall.dao.entity.Products;
import com.mall.mymall.dao.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 缓存商品数据
     *
     * @param list 提交内容
     */
    public void saveProductList(List<Products> list) {
        String json = JSON.toJSONString(list);
        redisTemplate.opsForValue().set("productList", json, 2, TimeUnit.HOURS);
    }

    /**
     * 提取商品数据
     *
     * @return 响应结果
     */
    public List<Products> getProductList() {
        String Json = redisTemplate.opsForValue().get("productList");
        if (Json == null || Json.isEmpty()) {
            return List.of();
        }
        return JSON.parseArray(Json, Products.class);
    }

    /**
     * 保存查询数据
     *
     * @param key  查询文本
     * @param list 提交内容
     */
    public void setSearchListToRedis(String key, List<Products> list) {
        String key1 = new String(key.getBytes(), StandardCharsets.UTF_8);
        String json = JSON.toJSONString(list);
        redisTemplate.opsForValue().set(key1, json, 1, TimeUnit.HOURS);
    }

    /**
     * 用于搜索功能 根据查询的键得到值
     *
     * @param key 查询文本
     * @return 响应数据
     */
    public List<Products> getProductListByKey(String key) {
        String key1 = new String(key.getBytes(), StandardCharsets.UTF_8);
        String Json = redisTemplate.opsForValue().get(key1);
        if (Json == null || Json.isEmpty()) {
            return List.of();
        }
        System.out.println("redis中读取到的数据：" + Json);
        return JSON.parseArray(Json, Products.class);
    }

    public void saveUser(String username,Object data) {
//        String key = username;
        String json = JSON.toJSONString(data);
        redisTemplate.opsForValue().set(username, json, 2, TimeUnit.HOURS);
    }

    /**
     * 从缓存中读取user
     *
     * @param username 存储键
     * @return 返回响应对象
     */
    public String loadUser(String username) {
        String Json = redisTemplate.opsForValue().get(username);
        if (Json == null || Json.isEmpty()) {
            return null;

        }
        return Json;
    }

    public String getUser(String username) {
        return redisTemplate.opsForValue().get(username);
    }
}
